package org.asdtiang.study.groovy.dynamic

class Foo {
   String prop
   def bar() { "bar" }
   def bar(String name) { "bar $name" }
   def add(Integer one, Integer two) { one + two}
}


def f = new Foo()

if(f.metaClass.respondsTo(f, "bar")) {
   println "bar"
}

if(f.metaClass.respondsTo(f, "bar", String)) {
   // do stuff
}

if(!f.metaClass.respondsTo(f, "bar", Integer)) {
   // do stuff
}

if(f.metaClass.respondsTo(f, "add", Integer, Integer)) {
   // do stuff
}

if(f.metaClass.hasProperty(f, "prop")) {
  // do stuff
}
println f.metaClass.metaMethods


/**
 * 方法动态访问
 * @return
 */
class Dog {
	def bark() { println "woof!" }
	def sit() { println "(sitting)" }
	def jump() { println "boing!" }
  }
  
  def doAction( animal, action ) {
	animal."$action"()                  //action name is passed at invocation
  }
  
  def rex = new Dog()
  
  doAction( rex, "bark" )               //prints 'woof!'
  doAction( rex, "jump" )               //prints 'boing!'
  
  
  class XmlBuilder {
	  def out
	  XmlBuilder(out) { this.out = out }
	  def invokeMethod(String name, args) {
		  out << "<$name>"
		  if(args[0] instanceof Closure) {
			   args[0].delegate = this
			   args[0].call()
		  }
		  else {
			  out << args[0].toString()
		  }
		  out << "</$name>"
	  }
   }
   def xml = new XmlBuilder(new StringBuffer())
   xml.html {
	   head {
		   title "Hello World"
	   }
	   body {
		   p "Welcome!"
	   }
   }
   
  

